/**
 * 数据实时更新服务
 * 提供WebSocket连接和定时更新机制
 */
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

class RealtimeDataService {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 5000
    this.heartbeatInterval = null
    this.heartbeatTimeout = 30000
    this.lastHeartbeat = null
    this.isConnected = false
    this.isManualDisconnect = false
    
    // 订阅者列表
    this.subscribers = new Map()
    
    // 数据缓存
    this.dataCache = reactive({
      stats: {},
      trends: {},
      teamPerformance: {},
      lastUpdate: null
    })
    
    // 定时更新任务
    this.updateTasks = new Map()
  }
  
  /**
   * 连接WebSocket
   */
  connect() {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      return Promise.resolve()
    }
    
    return new Promise((resolve, reject) => {
      try {
        this.ws = new WebSocket('ws://localhost:9090/ws/dashboard')
        
        this.ws.onopen = () => {
          console.log('📊 仪表盘数据服务连接成功')
          this.isConnected = true
          this.reconnectAttempts = 0
          this.startHeartbeat()
          this.authenticate()
          resolve()
        }
        
        this.ws.onmessage = (event) => {
          this.handleMessage(event)
        }
        
        this.ws.onclose = (event) => {
          console.log('📊 仪表盘数据服务连接关闭:', event.code, event.reason)
          this.isConnected = false
          this.stopHeartbeat()
          
          if (!this.isManualDisconnect && event.code !== 1000) {
            this.scheduleReconnect()
          }
        }
        
        this.ws.onerror = (error) => {
          console.error('📊 仪表盘数据服务连接错误:', error)
          reject(error)
        }
        
      } catch (error) {
        console.error('📊 创建WebSocket连接失败:', error)
        reject(error)
      }
    })
  }
  
  /**
   * 断开连接
   */
  disconnect() {
    this.isManualDisconnect = true
    this.stopHeartbeat()
    
    if (this.ws) {
      this.ws.close(1000, 'Manual disconnect')
      this.ws = null
    }
    
    this.clearUpdateTasks()
  }
  
  /**
   * 认证
   */
  authenticate() {
    const token = localStorage.getItem('token')
    if (token) {
      this.send({
        type: 'auth',
        token: token,
        timestamp: Date.now()
      })
    }
  }
  
  /**
   * 发送消息
   */
  send(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(message))
    } else {
      console.warn('📊 WebSocket未连接，无法发送消息')
    }
  }
  
  /**
   * 处理接收到的消息
   */
  handleMessage(event) {
    try {
      const message = JSON.parse(event.data)
      
      switch (message.type) {
        case 'auth_success':
          console.log('📊 仪表盘数据服务认证成功')
          this.requestInitialData()
          break
          
        case 'auth_failed':
          console.error('📊 仪表盘数据服务认证失败')
          break
          
        case 'pong':
          this.lastHeartbeat = Date.now()
          break
          
        case 'stats_update':
          this.updateStatsData(message.data)
          break
          
        case 'trends_update':
          this.updateTrendsData(message.data)
          break
          
        case 'team_performance_update':
          this.updateTeamPerformanceData(message.data)
          break
          
        case 'error':
          console.error('📊 服务器错误:', message.message)
          break
          
        default:
          console.log('📊 收到未知消息类型:', message.type)
      }
    } catch (error) {
      console.error('📊 解析消息失败:', error)
    }
  }
  
  /**
   * 请求初始数据
   */
  requestInitialData() {
    this.send({
      type: 'request_data',
      data: {
        stats: true,
        trends: true,
        teamPerformance: true
      }
    })
  }
  
  /**
   * 更新统计数据
   */
  updateStatsData(data) {
    this.dataCache.stats = { ...this.dataCache.stats, ...data }
    this.dataCache.lastUpdate = Date.now()
    
    // 通知订阅者
    this.notifySubscribers('stats', data)
  }
  
  /**
   * 更新趋势数据
   */
  updateTrendsData(data) {
    this.dataCache.trends = { ...this.dataCache.trends, ...data }
    this.dataCache.lastUpdate = Date.now()
    
    // 通知订阅者
    this.notifySubscribers('trends', data)
  }
  
  /**
   * 更新团队绩效数据
   */
  updateTeamPerformanceData(data) {
    this.dataCache.teamPerformance = { ...this.dataCache.teamPerformance, ...data }
    this.dataCache.lastUpdate = Date.now()
    
    // 通知订阅者
    this.notifySubscribers('teamPerformance', data)
  }
  
  /**
   * 订阅数据更新
   */
  subscribe(type, callback) {
    if (!this.subscribers.has(type)) {
      this.subscribers.set(type, new Set())
    }
    
    this.subscribers.get(type).add(callback)
    
    // 返回取消订阅函数
    return () => {
      const subscribers = this.subscribers.get(type)
      if (subscribers) {
        subscribers.delete(callback)
        if (subscribers.size === 0) {
          this.subscribers.delete(type)
        }
      }
    }
  }
  
  /**
   * 通知订阅者
   */
  notifySubscribers(type, data) {
    const subscribers = this.subscribers.get(type)
    if (subscribers) {
      subscribers.forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('📊 通知订阅者失败:', error)
        }
      })
    }
  }
  
  /**
   * 启动心跳
   */
  startHeartbeat() {
    this.stopHeartbeat()
    
    this.heartbeatInterval = setInterval(() => {
      if (this.isConnected) {
        this.sendPing()
      } else {
        this.stopHeartbeat()
      }
    }, this.heartbeatTimeout)
  }
  
  /**
   * 停止心跳
   */
  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
  }
  
  /**
   * 发送ping
   */
  sendPing() {
    this.send({
      type: 'ping',
      timestamp: Date.now()
    })
  }
  
  /**
   * 安排重连
   */
  scheduleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('📊 达到最大重连次数，停止重连')
      return
    }
    
    this.reconnectAttempts++
    const delay = Math.min(this.reconnectInterval * this.reconnectAttempts, 30000)
    
    console.log(`📊 ${delay/1000}秒后尝试第${this.reconnectAttempts}次重连`)
    
    setTimeout(() => {
      if (!this.isManualDisconnect) {
        this.connect().catch(error => {
          console.error('📊 重连失败:', error)
        })
      }
    }, delay)
  }
  
  /**
   * 添加定时更新任务
   */
  addUpdateTask(name, task, interval) {
    this.updateTasks.set(name, {
      task,
      interval,
      timer: setInterval(task, interval)
    })
  }
  
  /**
   * 移除定时更新任务
   */
  removeUpdateTask(name) {
    const task = this.updateTasks.get(name)
    if (task) {
      clearInterval(task.timer)
      this.updateTasks.delete(name)
    }
  }
  
  /**
   * 清除所有定时更新任务
   */
  clearUpdateTasks() {
    this.updateTasks.forEach(task => {
      clearInterval(task.timer)
    })
    this.updateTasks.clear()
  }
  
  /**
   * 获取缓存数据
   */
  getCachedData(type) {
    return this.dataCache[type] || {}
  }
  
  /**
   * 获取所有缓存数据
   */
  getAllCachedData() {
    return { ...this.dataCache }
  }
  
  /**
   * 检查连接状态
   */
  isWebSocketConnected() {
    return this.isConnected && this.ws && this.ws.readyState === WebSocket.OPEN
  }
  
  /**
   * 手动刷新数据
   */
  refreshData() {
    if (this.isWebSocketConnected()) {
      this.requestInitialData()
    } else {
      console.warn('📊 WebSocket未连接，无法刷新数据')
    }
  }
}

// 创建单例实例
const realtimeDataService = new RealtimeDataService()

// 导出服务实例和工具函数
export default realtimeDataService

// 导出工具函数
export const useRealtimeData = () => {
  return {
    // 连接服务
    connect: () => realtimeDataService.connect(),
    
    // 断开连接
    disconnect: () => realtimeDataService.disconnect(),
    
    // 订阅数据更新
    subscribe: (type, callback) => realtimeDataService.subscribe(type, callback),
    
    // 获取缓存数据
    getCachedData: (type) => realtimeDataService.getCachedData(type),
    
    // 获取所有缓存数据
    getAllCachedData: () => realtimeDataService.getAllCachedData(),
    
    // 检查连接状态
    isConnected: () => realtimeDataService.isWebSocketConnected(),
    
    // 手动刷新数据
    refreshData: () => realtimeDataService.refreshData(),
    
    // 添加定时更新任务
    addUpdateTask: (name, task, interval) => realtimeDataService.addUpdateTask(name, task, interval),
    
    // 移除定时更新任务
    removeUpdateTask: (name) => realtimeDataService.removeUpdateTask(name)
  }
}

// 导出数据缓存（响应式）
export const dataCache = realtimeDataService.dataCache
